import express from 'express';
import {AlipayFormData, AlipaySdk} from 'alipay-sdk';
import bodyParser from 'body-parser'
import cors from 'cors'

// 存储验证码（生产环境建议使用Redis）
const smsCodes = new Map();

const app = express();
const PORT = 8081;

//跨域设置
app.use(cors({
    origin: 'http://localhost:5173',
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(bodyParser.json()) // 支持 json 格式
app.use(bodyParser.urlencoded({extended : true}))//用来解析 request 中 body的 urlencoded字符

const alipaySdk = new AlipaySdk({
    //开放平台上创建应用时生成的 appId
    appId: '9021000153612657',
    // 签名算法,默认 RSA2
    signType: 'RSA2',
    // 支付宝网关地址 ，沙箱环境下使用时需要修改 正式线上的时候换成 https://openapi.alipay.com/gateway.do
    gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do',
    //支付宝公钥
    alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtArAIMe0IA8lXEs4fz5L/N2b5stoFbi5vfcdryKQyOSnBgkuQYkE+J2xfeZbfLML6rBdPZaOQ3AKgpxbfrt+EaaO2eFnfKG9Gwrsj2oLoFnbSSpIeW16mR8ienCExgB+Zn0EGpTaXnLoPjbskowo6KtBXvar/3kNAgJRXve0DLG6bFs6xhBC26B6lg5Jt0tgEJ7KNMJpdmHFJH+z0zWoVnrGvBSu/iqLZER+AhkpgI39S5lij2w0HEUKuQX7UI37deTx32GT26sOyAinndVRms/nqKsNnW4EKqo2EHEWdyqcLvlD3V01h5bxEZHeow33DLPpBLpiXf7CZrAvC0Vp6wIDAQAB',
    //应用私钥
    privateKey:'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC0glPU5y+a45LFUwI81gYITcO0K8fSh7+8ZvaH/dpsMJ8VZVpGD4r/AUmKg7wk4GRl+7EozXXrFVRUGTA5gw92Xmq29ZETdRRDUPuTM6DiVXnQDo04FLyh40NwQzUSdbBDZzlysb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gFibbmm+aCSDDGHpLvUSK/25XMwO202o/qoY/AMsHGHiYLsCWQjMOGD9Slm5sdrmiX+68mgLd+43rv008DGw8dVryZItEL+5Z1rRGxKk4haoxHRYvBo3tJMXA2LTAUI5iDV5lgUc5scr9l5BIVWoJHaAtYaeVryhMqULoA3MjmJpAoGBAL2FeKhtSEw7aqxzu4TBdPIDXo81jRwzycc5zEtokDjRKeS2BIdYrKQmNfplueUx6ezJ6+TJAHYaFoVZnIqsQTlsNfRUZtQ8CA+CzBnP0zbBc5aUcHCkHQTBY2hopbE0wNlexFZamTHQZ/R+aK71TKbkClXwh3jmX3VpADGHiAoW'
});

//获取支付页面的外部链接
app.post('/pay',function (req, res) {
    console.log('订单信息',req.body)
    const {oid,title,total_amount,goods_detail}=req.body

    const bizContent = {
        //订单号，唯一
        out_trade_no: oid,
        product_code: "FAST_INSTANT_TRADE_PAY",
        subject: title,
        body: "",
        goods_detail:goods_detail,
        total_amount: total_amount
    }
    // 支付页面接口，返回支付链接，交由用户打开，会跳转至支付宝网站
    const url = alipaySdk.pageExecute('alipay.trade.page.pay', 'GET', {
        bizContent,
        //返回订单页面
        returnUrl: 'http://localhost:5173/userCenter/order'
    });
    res.json(url)
})

app.get('/check',async function (req, res) {
    console.log('查询订单号',req.query.oid)
    const {oid}=req.query
    const bizContent = {
        out_trade_no: oid,
    }

    try {
        const result = await alipaySdk.exec("alipay.trade.query", {
            bizContent
        });
        console.log(result)
        res.json(result)
    } catch (error) {
        console.error('Alipay check error:', error);
        // 向前端返回一个统一的错误格式，而不是让服务器崩溃
        res.status(500).json({
            code: '50000', // 自定义错误码
            msg: 'Failed to check trade status with Alipay',
            subMsg: error.message
        });
    }
})

app.post('/refund',async function (req,res) {
    const {refund_amount,out_trade_no}=req.body
    console.log(`订单号${out_trade_no}进行退款,退款金额${refund_amount}`)
    const bizContent={
        refund_amount:refund_amount,
        out_trade_no:out_trade_no,
        refund_reason:'正常退款',
    }
    const result = await alipaySdk.exec("alipay.trade.refund", {
        bizContent
    })
    console.log(result)
    res.json(result)
})

app.get('/refund',async function (req,res) {
    const {out_trade_no}=req.query
    console.log(`订单${out_trade_no}退款状态`)
    const result=await alipaySdk.exec("alipay.trade.fastpay.refund.query", {
        bizContent:{
            out_request_no:out_trade_no,
            out_trade_no:out_trade_no
        }
    })
    console.log(result)
    res.json(result)
})

// 发送短信验证码接口
app.post('/user/sms/send', (req, res) => {
    try {
        const { phone } = req.body;
        
        if (!phone || phone.length !== 11) {
            return res.json({ code: 400, message: '手机号格式不正确' });
        }
        
        // 生成4位随机验证码
        const code = Math.random().toString().slice(2, 6);
        
        // 存储验证码，设置5分钟过期时间
        smsCodes.set(phone, {
            code: code,
            timestamp: Date.now(),
            expires: Date.now() + 5 * 60 * 1000 // 5分钟过期
        });
        
        // 在控制台输出验证码（模拟短信发送）
        console.log(`📱 短信验证码发送：手机号 ${phone} -> 验证码 ${code}`);
        
        res.json({ 
            code: 200, 
            message: '验证码发送成功',
            data: { phone: phone }
        });
    } catch (error) {
        console.error('短信发送错误:', error);
        res.json({ code: 500, message: '短信发送失败' });
    }
});

// 短信验证码登录接口
app.post('/user/login/sms', (req, res) => {
    const { phone, code } = req.body;
    
    if (!phone || !code) {
        return res.json({ code: 400, message: '手机号和验证码不能为空' });
    }
    
    // 检查验证码是否存在
    const smsData = smsCodes.get(phone);
    if (!smsData) {
        return res.json({ code: 400, message: '验证码不存在或已过期' });
    }
    
    // 检查验证码是否过期
    if (Date.now() > smsData.expires) {
        smsCodes.delete(phone); // 清除过期验证码
        return res.json({ code: 400, message: '验证码已过期' });
    }
    
    // 验证验证码是否正确
    if (smsData.code !== code) {
        return res.json({ code: 400, message: '验证码错误' });
    }
    
    // 验证成功，清除验证码
    smsCodes.delete(phone);
    
    // 模拟用户登录成功（这里应该查询数据库获取真实用户信息）
    const userInfo = {
        id: 1,
        phone: phone,
        username: `用户_${phone.slice(-4)}`,
        role: 'user', // 默认普通用户
        token: 'mock_token_' + Date.now()
    };
    
    console.log(`✅ 短信登录成功：手机号 ${phone}，用户 ${userInfo.username}`);
    
    res.json({ 
        code: 200, 
        message: '登录成功',
        data: userInfo
    });
});

// 密码登录接口（已存在，这里添加模拟数据）
app.post('/user/login', (req, res) => {
    const { uid, password } = req.body;
    
    // 模拟用户验证（生产环境应该查询数据库）
    if (uid && password) {
        const userInfo = {
            id: 1,
            username: uid,
            role: uid === 'admin' ? 'admin' : 'user',
            token: 'mock_token_' + Date.now()
        };
        
        console.log(`✅ 密码登录成功：用户 ${uid}`);
        
        res.json({ 
            code: 200, 
            message: '登录成功',
            data: userInfo
        });
    } else {
        res.json({ code: 400, message: '账号或密码错误' });
    }
});

app.listen(PORT, () => {
    console.log(`Server is running at http://localhost:${PORT}`);
});
